package com.example.campusrear.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.campusrear.Service.adminService;
import com.example.campusrear.Utils.R;
import com.example.campusrear.entity.Admin;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/admin")
public class adminController {
    @Resource
    private adminService adminService;

    //    登录
    @PostMapping("/login")
    public R<Admin> login(@RequestBody Admin admin, HttpServletRequest request){
        //密码进行加密
        String password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        //首先判断手机号是否存在
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getPhone,admin.getPhone());
        Admin a = adminService.getOne(wrapper);
        //存在校验密码直接登录
        if(a!=null){
            wrapper.eq(Admin::getPassword,password);
            Admin Ruser = adminService.getOne(wrapper);
            if(adminService.getOne(wrapper)==null){
                return R.error("密码错误");
            }
//            request.getSession().setAttribute("userID",Ruser.getId());
            return R.success(Ruser);
        }
        //不存在,保存信息再返回
        return R.error("账号不存在");
    }

    @PostMapping("/update")
    public R<String> update(@RequestBody Admin admin){
        adminService.updateById(admin);
        return R.success("修改成功");
    }
    @PostMapping("/save")
    public R<String> save(@RequestBody Admin admin){
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getPhone,admin.getPhone());
        Admin a = adminService.getOne(wrapper);
        if(a!=null){
            return R.error("手机号已存在");
        }
        adminService.save(admin);
        return R.success("添加成功");
    }
}
